import { format } from "@/utils/format";

/**
 * 扫码条形码和二维码
 * scanType:CODE_128 直接返回扫描结果
 * scanType:QR_CODE 返回对象
 */
export const onScanCode = () => {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			onlyFromCamera: true,
			scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
			success: function (res) {
				// console.log('条码类型：' + res.scanType);
				// console.log('条码内容：' + res.result);
				if (res.scanType == 'QR_CODE') {
					const params = format.parseQueryParam(res.result);
					resolve({
						scanType: res.scanType,
						params: params,
					});
				} else if (res.scanType == 'CODE_128') {
					resolve({
						scanType: res.scanType,
						result: res.result,
					});
				} else {
					reject('不支持的条码类型');
				}
			},
			fail: err => {
				reject(err);
			}
		});
	})
}
/**
 * 下载图片并保存到相册
 * @param {*} imageUrls 图片地址
 * @returns 
 */
export const downloadImages = async (imageUrls : string[]) => {
	const downloadPromises = imageUrls.map(url => {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url,
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.tempFilePath);
					} else {
						reject(new Error(`Download failed with status code ${res.statusCode}`));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	});

	return new Promise((resolve, reject) => {
		Promise.all(downloadPromises).then((tempFilePaths : any[]) => {
			// 可以选择保存到相册或其他操作
			tempFilePaths.forEach((tempFilePath : string) => {
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						console.log('图片已保存到相册');
						resolve('');
					},
					fail: (err) => {
						console.error('保存图片到相册失败', err);
						reject('保存图片到相册失败');
					}
				});
			});
		}).catch(error => {
			console.error('下载过程中出现错误', error);
			reject('下载过程中出现错误');
		})
	});
}